package com.sunfeng.netty.atguigu.linebasedframedecoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;


/**
 * @author sunfeng
 * @date 2021/05/19 11:14
 **/
@Slf4j
public class TimeServerHandler extends ChannelInboundHandlerAdapter  {

    private int counter;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body=(String)msg;
        log.info("服务端收到客户端发来的的消息是: " + body + "计数器为：" + ++counter);


        // 判断客户端发来的消息和服务端预设值的消息是否相同
        // 如果相同就返回给客户端当前的时间
        String str = "NOW TIME IS NOW";
        String nowTime = "NOTE RIGHT";
        if (str.trim().equals(body.trim())){
            nowTime = new Date().toString();
        }


        ByteBuf byteBuf = Unpooled.copiedBuffer((nowTime + System.getProperty("line.separator")).getBytes());
        // 写回给客户端
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
